<?php defined('SYSPATH') or die('No direct access allowed.');


class Model_Project_Appreciation extends ORM {

		// Relationships
	protected $_belongs_to = array('project' => array('model' => 'desktop_project','foreign_key' => 'project_id'),
                                       'user'    => array('model' => 'user', 'foreign_key' => 'user_id'));
        
        public function get_appreciations($project_id, $limit = false)
        {
             $temp_appreciations = DB::select('user_profiles.name',
                                            'user_profiles.surname',
                                            'user_profiles.description',
                                            'user_profiles.url',
                                            array('user_profiles.file_id','photo'),
                                            array('files.id','file_id'),
                                            array('files.name','file_name'),
                                            array('files.extension','file_extension'))
                                   ->from('project_appreciations')
                                   ->join('users')->on('project_appreciations.user_id', '=', 'users.id')
                                   ->join('user_profiles')->on('user_profiles.user_id', '=', 'users.id')
                                   ->join('files','LEFT')->on('files.id', '=', 'user_profiles.file_id')
                                   ->where('project_appreciations.project_id', '=', $project_id);
            
             if ($limit)
                $temp_appreciations->limit($limit);
                  
             $temp_appreciations =  $temp_appreciations->as_object()->execute();
             
             $appreciations = array();
             foreach($temp_appreciations as $appreciation)
             {   
                 $appreciation->photo = Media::get_file_path($appreciation->file_name, 
                                                             $appreciation->file_id, 
                                                             $appreciation->file_extension, 
                                                             true, 
                                                             'mini_square', 
                                                             false);
                 
                 $appreciations[] = $appreciation;
             }
              return $appreciations;
        }
        
        public function is_appreciated($project_id, $user_id)
        {
            $is_appreciated = DB::select(array('COUNT("*")','total_rows'))
                                ->from('project_appreciations')
                                ->where('project_id', '=', $project_id)
                                ->where('user_id', '=', $user_id)
                                ->as_object()
                                ->execute();
            
            return (bool)$is_appreciated[0]->total_rows;
        }
}